﻿using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace Export2Excel
{
    public class LevelInfo
    {
        private List<LevelType> types;

        public LevelInfo()
        {
            types = new List<LevelType>()
            {
                new LevelType(@"^[一二三四五六七八九十]*、(.*)", 1),
                new LevelType(@"^（[一二三四五六七八九十]*）(.*)", 2),
                new LevelType(@"^\d*[．、](.*)", 3),
                new LevelType(@"^（\d*）(.*)", 4),
                new DataLevel()
            };
        }

        public int GetLevelInfo(string input, out string matchResult)
        {
            int level = -1;
            matchResult = string.Empty;

            foreach (var item in types)
            {
                if (item.IsMatched(input, out matchResult))
                {
                    level = item.Level;
                    break;
                }
            }

            return level;
        }
    }

    #region LevelType

    public class LevelType
    {
        public string Exp { get; private set; }
        public int Level { get; private set; }
        private Regex _regex;

        public LevelType(string exp, int level)
        {
            Level = level;
            Exp = exp;
            _regex = new Regex(Exp, RegexOptions.IgnoreCase | RegexOptions.Singleline);
        }

        public virtual bool IsMatched(string input, out string value)
        {
            value = string.Empty;

            if (string.IsNullOrEmpty(input))
            {
                return false;
            }

            Match match = _regex.Match(input.Trim());
            bool matched = match.Success;

            if (matched)
            {
                value = match.Groups[1].Value;
            }

            return matched;
        }
    }

    public class DataLevel : LevelType
    {
        public DataLevel()
            : base(@"", 5)
        { }

        public override bool IsMatched(string input, out string value)
        {
            value = string.Empty;

            if (string.IsNullOrEmpty(input))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
    #endregion
}
